package guda.house.web.security;

import org.springframework.beans.factory.InitializingBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by well on 15/11/21.
 */
public class StarkAuthFilter implements Filter,InitializingBean {

    private StarkAuthChecker starkAuthChecker ;

    private StarkAuthChecker.Callback callback;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            String requestURI = ((HttpServletRequest) request).getRequestURI();
//            if("/".equals(requestURI)){
//                try {
//                    ((HttpServletResponse)response).sendRedirect("/home/index.htm");
//                    return ;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            }
            if (requestURI.startsWith("/help/")||requestURI.startsWith("/home/")||"/".equals(requestURI)||requestURI.startsWith("/front/wx/")) {
                chain.doFilter(request, response);
            } else if (((HttpServletRequest) request).getRequestURI().endsWith(".do")){
                chain.doFilter(request, response);
            }else {
                boolean check = starkAuthChecker.check((HttpServletRequest) request, (HttpServletResponse) response);
                if (check) {
                    chain.doFilter(request, response);
                }
            }
        }

    }

    @Override
    public void destroy() {

    }

    public void setCallback(StarkAuthChecker.Callback callback) {
        this.callback = callback;
    }

    public void setPageAuthChecker(StarkAuthChecker starkAuthChecker) {
        this.starkAuthChecker = starkAuthChecker;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(starkAuthChecker == null) {
            starkAuthChecker = new StarkAuthChecker();
        }
        if(callback != null) {
            starkAuthChecker.setCallback(callback);
        }
    }
}
